package com.wefans.wefansapp.activity;

import java.io.File;
import java.util.Hashtable;
import java.util.Set;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.widget.DrawerLayout;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.wefans.wefansapp.R;
import com.wefans.wefansapp.common.tool.data.MFDataManager;
import com.wefans.wefansapp.common.tool.data.ResDefaultData;
import com.wefans.wefansapp.common.tool.data.ResGetCountry;
import com.wefans.wefansapp.common.tool.debug.MFDebug;
import com.wefans.wefansapp.common.tool.network.MFNetworkManager;
import com.wefans.wefansapp.common.tool.network.MFNetworkManager.IOnNetworkListener;
import com.wefans.wefansapp.common.tool.network.model.NetJsonData;
import com.wefans.wefansapp.common.tool.network.model.NetMessage;
import com.wefans.wefansapp.common.tool.popup.CameraDialog;
import com.wefans.wefansapp.common.tool.popup.ChangePasswordDialog;
import com.wefans.wefansapp.common.tool.popup.ChangePasswordDialog.OnChangePwListener;
import com.wefans.wefansapp.common.tool.popup.MemberLeaveDialog;
import com.wefans.wefansapp.common.tool.popup.MemberLeaveDialog.OnLeaveListener;
import com.wefans.wefansapp.common.tool.preference.MFSharedPreference;
import com.wefans.wefansapp.common.tool.utils.MFCountryCodeUtil;
import com.wefans.wefansapp.common.tool.utils.MFToastUtil;

public class MyinfoActivity extends BaseActivity {

	private static final int REQ_CAMERA = 101;
	
	private DrawerLayout   m_DrawerLayout  = null;
    private FrameLayout    m_DrawerView    = null;
	
	private Context mContext = null;
	private ImageView mIvPicture = null;
	private TextView mTvPictureName = null;
	private TextView mTvName = null;
	private TextView mTvId = null;
	private TextView mTvPhoneNum = null;
	private TextView mTvNickName = null;
	private TextView mTvCountry = null;
	private LinearLayout mLlCountrySelector = null;
	private EditText mEtRecommender = null;
	private Button mBtnChangePassword = null;
	private Button mBtnExitMember = null;
	private Button mBtnLogout = null;
	private Button mBtnChangeInfo = null;
	
	private int resize_h;
	private MFSharedPreference mPrf = null;
	
	public static final String MyPhotoPath = Environment.getExternalStorageDirectory()+"/FandomS/";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
		mContext = this;
		mPrf = new MFSharedPreference(this);
		
		setContentView(R.layout.activity_main);
		
		initialize();
        installEvent();
	}
	
	@Override
    protected void onPause()
    {
        MFDebug.d(">> onPause()");
        
        notifyDoClaseDrawerMenu();
        
        super.onPause();
    }

    @Override
    protected void notifyDoClaseDrawerMenu()
    {
        MFDebug.d(">> notifyDoClaseDrawerMenu()");
        
        super.notifyDoClaseDrawerMenu();
        
        if( m_DrawerLayout == null ) {
            MFDebug.e(new Exception("There are NO Drawer-Layout"));
            return;
        }
        
        if( m_DrawerView == null ) {
            MFDebug.e(new Exception("There are NO Drawer-View"));
            return;
        }
        
        m_DrawerLayout.closeDrawer(m_DrawerView);
        m_sdQuickMenu.close();
    }
	
	private void initialize()
    {
        MFDebug.d(">> initialize()");
        
        //Contents layout adding
        FrameLayout containerContents = (FrameLayout) findViewById(R.id.FL_MAIN_CONTAINER);
        addContentsLayout(containerContents, R.layout.activity_myinfo);
        addQuickMenuLayout(containerContents);
        
        //Drawer menu adding
        m_DrawerView = (FrameLayout) findViewById(R.id.FL_DRAWER_LAYOUT);
        addDrawerLayout(m_DrawerView);
        
        //set drawer layout (root)
        m_DrawerLayout = (DrawerLayout) findViewById(R.id.DL_MAIN_NAVIGATION_LAYOUT);
    }
    
    private void installEvent()	
    {
        MFDebug.d(">> installEvent()");
        
        ((ImageButton) findViewById(R.id.IB_MAIN_HEADER_LEFT_BUTTON)).setOnClickListener(this);
        ((ImageButton) findViewById(R.id.IB_MAIN_HEADER_RIGHT_BUTTON)).setOnClickListener(this);
        
        mIvPicture 			= (ImageView)findViewById(R.id.IV_PICTURE);
        mTvPictureName 		= (TextView)findViewById(R.id.TV_PICTURE_NAME);
    	mTvName 			= (TextView)findViewById(R.id.TV_NAME);
    	mTvId 				= (TextView)findViewById(R.id.TV_ID);
    	mTvPhoneNum 		= (TextView)findViewById(R.id.TV_PHONE_NUMBER);
    	mTvNickName 		= (TextView)findViewById(R.id.TV_NICKNAME);
    	mTvCountry 			= (TextView)findViewById(R.id.TV_COUNTRY);
		mLlCountrySelector 	= (LinearLayout)findViewById(R.id.LL_COUNTRY_SELECT);
		mEtRecommender 		= (EditText)findViewById(R.id.ET_RECOMMENDER);
		mBtnChangePassword 	= (Button)findViewById(R.id.BTN_CHANGE_PASSWORD);
		mBtnExitMember 		= (Button)findViewById(R.id.BTN_EXIT_MEMBER);
		mBtnLogout 			= (Button)findViewById(R.id.BTN_LOGOUT);
		mBtnChangeInfo 		= (Button)findViewById(R.id.BTN_INFO_CHANGE);
		
		mIvPicture.setOnClickListener(this);
		mLlCountrySelector.setOnClickListener(this);
		mBtnChangePassword.setOnClickListener(this);
		mBtnExitMember.setOnClickListener(this);
		mBtnLogout.setOnClickListener(this);
		mBtnChangeInfo.setOnClickListener(this);
				
		setMyInfo();
	}
	
    private void setMyInfo() {
    	
    	setMyPhoto();
    	
    	MFDataManager dataMng = MFDataManager.getInstance(getApplicationContext());
    	if (dataMng != null && dataMng.getUserInfo() != null) {
    		mTvPictureName.setText(dataMng.getUserInfo().getNickname());
         	mTvName.setText(dataMng.getUserInfo().getName());
         	mTvId.setText(dataMng.getMebmerIdx());
         	mTvPhoneNum.setText(dataMng.getUserInfo().getMobile());
         	mTvNickName.setText(dataMng.getUserInfo().getNickname());
         	mTvCountry.setText(MFCountryCodeUtil.getValueByCode(mContext, dataMng.getUserInfo().getCountry()));
         	mEtRecommender.setText(dataMng.getUserInfo().getRecommend());
    	}
    }
    
    private void setMyPhoto() {
    	resize_h = (int) getResources().getDimension(R.dimen.x_370);
		
		String photourl= MyPhotoPath+"tmp_" + MFDataManager.getInstance(getApplicationContext()).getMebmerIdx() + ".jpg";
		File photofile=new File(photourl);
		if(!photofile.exists()){
			Bitmap image = BitmapFactory.decodeResource(getResources(), R.drawable.myinfo_img_default);
			Bitmap resized = Bitmap.createScaledBitmap(image, resize_h, resize_h, true);		
//			mmy_img.setImageBitmap(resized);
//			mmy_img.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
		}
		else{						
			Bitmap photo = BitmapFactory.decodeFile(photourl);
			if(photo==null){
				photofile.delete();
				Bitmap image = BitmapFactory.decodeResource(getResources(), R.drawable.myinfo_img_default);
				Bitmap resized = Bitmap.createScaledBitmap(image, resize_h, resize_h, true);		
//				mmy_img.setImageBitmap(resized);
//				mmy_img.setScaleType(ImageView.ScaleType.CENTER_INSIDE);				
			}
			else{
				Bitmap resized = Bitmap.createScaledBitmap(photo, resize_h, resize_h, true);
				mIvPicture.setImageBitmap(photo);
//				mmy_img.setImageBitmap(resized);
//				mmy_img.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
			}
		}
    }
	
	@Override
	public void onClick(View v) {
		
		Intent intent = null;
		
		switch (v.getId()) {
		case R.id.IB_MAIN_HEADER_LEFT_BUTTON :
            m_DrawerLayout.openDrawer(m_DrawerView);
            break;
		case R.id.IB_MAIN_HEADER_RIGHT_BUTTON:
			intent = new Intent(MyinfoActivity.this, MainActivity.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
	        startActivity(intent);
			finish();
			break;
		case R.id.IV_PICTURE:
			intent = new Intent(MyinfoActivity.this,CameraDialog.class);
	        startActivityForResult(intent, REQ_CAMERA);
	        break;
		case R.id.BTN_EXIT_MEMBER:
			new MemberLeaveDialog(mContext, new OnLeaveListener() {
				@Override
				public void onMemberLeave() {
					requestExitMember();
				}
			}).show();;				
			break;
		
		case R.id.BTN_LOGOUT:
			mPrf.setMem_idx("");
			intent = new Intent(MyinfoActivity.this,LoginActivity.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
	        startActivity(intent);
			finish();
			break;
		case R.id.LL_COUNTRY_SELECT:
			final String strItems[] = MFCountryCodeUtil.getValueList(mContext);
			int nSelect = MFCountryCodeUtil.getIndexByValue(mContext, mTvCountry.getText().toString());
			
			AlertDialog.Builder ab = new AlertDialog.Builder(MyinfoActivity.this);
		    ab.setTitle(getString(R.string.country));
			ab.setSingleChoiceItems(strItems, nSelect,
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int whichButton) {
							mTvCountry.setText(strItems[whichButton]);
							dialog.cancel();
						}
					});						
			ab.show();
			break;
		case R.id.BTN_CHANGE_PASSWORD:
			new ChangePasswordDialog(mContext, new OnChangePwListener() {
				
				@Override
				public void onChangePassword(String strOldPassword, String strNewPassword) {
					requestChangePassword(strOldPassword, strNewPassword);
				}
			}).show();;	
			break;
		
		case R.id.BTN_INFO_CHANGE:
			String strCountryCode = MFCountryCodeUtil.getCodeByValue(mContext, mTvCountry.getText().toString());
			String strRecommender = mEtRecommender.getText().toString();
			requestChangeMyInfo(strCountryCode, strRecommender);
			break;
		}
		super.onClick(v);
	}
	
	private void requestChangeMyInfo(String strCountryCode, String strRecommender) {
		
		String strUrl = MFNetworkManager.BASE_URL + "/app/set_user.php";
		
		Hashtable<String, String> body = new Hashtable<String, String>();
		body.put("mem_idx", MFDataManager.getInstance(getApplicationContext()).getMebmerIdx());
		body.put("recommend", strRecommender);
		body.put("country", strCountryCode);

		MFNetworkManager.getInstance(this).requestPostData(MFNetworkManager.REQUEST_CHANGE_MYINFO, strUrl, body, mNetworkListener);
	}
	
	private void requestChangePassword(String strOldPw, String strNewPw) {
		String strUrl = MFNetworkManager.BASE_URL + "/my/set_pass.php";

		Hashtable<String, String> body = new Hashtable<String, String>();
		body.put("mem_idx", MFDataManager.getInstance(getApplicationContext()).getMebmerIdx());
		body.put("passwd_current", strOldPw);
		body.put("passwd", strNewPw);
		
		MFNetworkManager.getInstance(this).requestPostData(MFNetworkManager.REQUEST_CHANGE_PASSWORD, strUrl, body, mNetworkListener);
	}
	
	private void requestExitMember() {
		String strUrl = MFNetworkManager.BASE_URL + "/my/set_out.php";
		
		Hashtable<String, String> body = new Hashtable<String, String>();
		body.put("mem_idx", MFDataManager.getInstance(getApplicationContext()).getMebmerIdx());
		
		MFNetworkManager.getInstance(this).requestPostData(MFNetworkManager.REQUEST_EXIT_MEMBER, strUrl, body, mNetworkListener);
	}
	
	IOnNetworkListener mNetworkListener = new IOnNetworkListener() {
		
		@Override
		public void onNetMessage(int resultCode, NetMessage message) {
			try {
	            //서버 여동 데이터
	            if( message instanceof NetJsonData ) {
	                long magicNum = ((NetJsonData) message).getMagicNum();
	                String json = ((NetJsonData) message).getResponseJson();
	                
	                if( json == null ) {
	                    throw new Exception("invalid json data");
	                }
	                
	                Gson gson = new Gson();
	                
	                ResDefaultData resultData = (ResDefaultData)gson.fromJson(json, ResDefaultData.class);
                    if( resultData == null ) {
                        throw new Exception("Gson parsing error");
                    }
	                
	                if (magicNum == MFNetworkManager.REQUEST_CHANGE_PASSWORD) {
	                	
	                    if (resultData.isSuccsess()) {
	                    } else {
	                    	MFToastUtil.NetResponseToast(getApplicationContext(), resultData.getResultcode(), resultData.getResultmsg());
	                    }
	                } else if (magicNum == MFNetworkManager.REQUEST_EXIT_MEMBER) {

	                	if (resultData.isSuccsess()) {
	                		mPrf.setMem_idx("");
	                		Intent intent = new Intent(MyinfoActivity.this, LoginActivity.class);
	    					intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
	    			        startActivity(intent);
	    					finish();
	                	} else {
	                		MFToastUtil.NetResponseToast(getApplicationContext(), resultData.getResultcode(), resultData.getResultmsg());
	                	}
	                } else if (magicNum == MFNetworkManager.REQUEST_CHANGE_MYINFO) {
	                	if (resultData.isSuccsess()) {
	                		Toast.makeText(mContext, "정보 변경 성공", Toast.LENGTH_SHORT).show();
	                	} else {
	                		MFToastUtil.NetResponseToast(getApplicationContext(), resultData.getResultcode(), resultData.getResultmsg());
	                	}
	                }
	            }	            
	        } catch(Exception e) {	        	
	            MFDebug.e(e);
	        }		
		}
	};	
	
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode != RESULT_OK) {
			return;
		}

		if (requestCode == REQ_CAMERA) {
			MFDebug.e("REQ_CAMERA");
			if (resultCode == RESULT_OK) {
				MFDebug.e("REQ_CAMERA");
				String photo_path = MyPhotoPath + "tmp_" + MFDataManager.getInstance(getApplicationContext()).getMebmerIdx() + ".jpg";
				File photofile = new File(photo_path);
				if (!photofile.exists()) {
					// default image
					MFDebug.e("REQ_CAMERA");
					Bitmap image = BitmapFactory.decodeResource(getResources(), R.drawable.myinfo_img_default);
					Bitmap resized = Bitmap.createScaledBitmap(image, resize_h, resize_h, true);
					mIvPicture.setImageResource(R.drawable.myinfo_img_default);
//					mmy_img.setImageBitmap(resized);
//					mmy_img.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
				} else {
					MFDebug.e("REQ_CAMERA");
					Bitmap photo = BitmapFactory.decodeFile(photo_path);
					if (photo == null) {
						MFDebug.e("이미지 없거나 잘못됐음");
						photofile.delete();
						Bitmap image = BitmapFactory.decodeResource(getResources(), R.drawable.myinfo_img_default);
						Bitmap resized = Bitmap.createScaledBitmap(image, resize_h, resize_h, true);
						mIvPicture.setImageResource(R.drawable.myinfo_img_default);
						// mmy_img.setImageBitmap(resized);
						// mmy_img.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
					} else {
						Bitmap resized = Bitmap.createScaledBitmap(photo, resize_h, resize_h, true);
						mIvPicture.setImageBitmap(photo);
						// mmy_img.setImageBitmap(resized);
						// mmy_img.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
						// Gloval checkphoto=new Gloval();
						// checkphoto.setCheckChangePhoto(true);
					}
				}
			}
		}
	}
}
